package com.cloudfun.campusshare.service.impl;

import com.cloudfun.campusshare.common.constant.RoleType;
import com.cloudfun.campusshare.entity.RoleEntity;
import com.cloudfun.campusshare.entity.UserRoleEntity;
import com.cloudfun.campusshare.repo.RoleEntityRepo;
import com.cloudfun.campusshare.repo.UserRoleEntityRepo;
import com.cloudfun.campusshare.service.UserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by Huqin on 2019/12/30
 */
@Slf4j
@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private RoleEntityRepo roleEntityRepo;

    @Autowired
    private UserRoleEntityRepo userRoleEntityRepo;

    @Override
    public String getAnyAdminUserId() {
        List<RoleEntity> adminRole = roleEntityRepo.findAllByType(RoleType.ADMIN.name());
        List<String> adminRoleIds = adminRole.stream().map(RoleEntity::getId).collect(Collectors.toList());
        List<UserRoleEntity> userRoleEntities = userRoleEntityRepo.findAllByRoleIdIn(adminRoleIds);
        Optional<String> adminIdOpt = userRoleEntities.stream().map(UserRoleEntity::getUserId).findAny();
        return adminIdOpt.get();
    }
}
